#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Time       :   10:03
# Author     : Y4
# Site       : 前台用户
# File       : client_user_view.py
import uuid

from flask import Blueprint, request

from App.common.client.get_client_user import get_user
from App.common.utils.util import rerep, single_dict, send_phone_code
from App.common.utils.valify import check_phone
from App.models.client import User

from App.plugins import cache


user = Blueprint('user', __name__, url_prefix='/client/user')


@user.route('/login', methods=['POST'])
def login():
    username = request.form.get('username')
    password = request.form.get('password')
    phone = request.form.get('phone')

    user = get_user(username) or get_user(phone)
    if not user:
        return rerep(msg='用户不存在', status=400)
    if not user.check_password(password):
        return rerep(msg='密码错误', status=400)
    if user.is_delete:
        return rerep(msg='该用户已注销', status=400)
    token = uuid.uuid4().hex
    cache.set(token, user.uuid, timeout=60 * 60 * 24 * 7)
    return rerep(msg="登录成功", data=token)


@user.route('/register', methods=['POST'])
def register():
    username = request.form.get('username')
    password = request.form.get('password')
    phone = request.form.get('phone')
    code = request.form.get('code')

    # 缓存中获取code,如果和传递过来的不相等
    cache_code = cache.get(phone)
    if cache_code != code:
        return rerep(msg="验证码或手机号码错误", status=400)

    user = User()           # 这个是另一个库的通用user
    user.username = username
    user.password = password
    user.phone = phone

    if not user.save():
        return rerep(msg="用户创建失败", status=400)

    # 不写或者写"all",返回全部..其余写的都是需要返回的字段
    return rerep(data=single_dict(user, "all"))


@user.route('/getphonecode')
def get_phone_code():
    phone = request.args.get('phone')
    # 验证电话号码是否正确
    re_phone = check_phone(phone)
    if phone is None or re_phone is None:
        return rerep(msg="手机号码不正确")

    # 获取缓存中的code
    cache_code = cache.get(re_phone)
    if cache_code:
        return rerep(msg="请勿频繁操作")

    # 手机发送code
    res = send_phone_code(re_phone)
    if res:
        result = res.json()
        if result.get('code') == 200:
            code = result.get('obj')
            cache.set(re_phone, code, timeout=60 * 60 * 24 * 30)  # 缓存5分钟,暂时1个月，方便调试
            return rerep(msg="发送成功")
        return rerep(msg="发送失败,请重新发送", status=400)